<template>
  <div style="height: 100%;display: flex;flex-direction: column">
    <el-row>
      <el-card style="width: 100%;">
        用户添加
        <span style="float: right">
            <el-button @click="()=>{$router.push('/user/list')}">回到列表页</el-button>
        </span>
      </el-card>
    </el-row>

    <el-row style="margin-top: 10px;flex: 1;display:flex;align-items: center;justify-content: center;">
      <el-card style="flex: 1;display: flex;justify-content: center">
        <el-form label-width="120px" :model="state.userAddInfo" ref="formRef" :rules="rules">
          <el-form-item label="用户名" prop="username">
            <el-input label="用户名" v-model="state.userAddInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input label="密码" v-model="state.userAddInfo.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input label="确认密码" v-model="state.userAddInfo.confirmPassword" type="password"></el-input>
          </el-form-item>
          <el-form-item label="加密方式" prop="encryptedType">
            <el-radio-group v-model="state.userAddInfo.encryptedType">
              <el-radio label="1">Bcrpt</el-radio>
              <el-radio label="2">Md5</el-radio>
              <el-radio label="3">不加密</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input label="邮箱" v-model="state.userAddInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input label="手机号" v-model="state.userAddInfo.phone"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realname">
            <el-input label="真实姓名" v-model="state.userAddInfo.realname"></el-input>
          </el-form-item>
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="state.userAddInfo.enabled">
              <el-radio :label="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="头像" prop="avatar" style="display: flex;align-items: center">
            <el-upload :action="UPLOAD_PATH" list-type="picture-card" :auto-upload="true" ref="uploadRef"
                       :on-change="uploadChange"
                        :limit="1"
                        name="file"
                       :file-list="state.fileList"
                       :on-success="uploadSuccess"
                       :headers="uploadHeaders"
                       :on-error="uploadError"
                       element-loading-text="正在上传"
                       v-loading="state.isUploading"
                       :before-upload="beforeUpload"

            >
                  <el-icon>
                    <Plus />
                  </el-icon>
             <template #file="{ file }">
                <el-row>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""  />
                  <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <el-icon>
                    <zoom-in />
                  </el-icon>
                </span>
                <span v-if="!state.disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                  <el-icon>
                    <Download />
                  </el-icon>
                </span>
                    <span v-if="!state.disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
               </el-row>
            </template>
            </el-upload>
            <el-dialog :append-to-body="true"  v-model="state.dialogVisible" style="display: flex;align-items: center;justify-content: center">
              <img w-full :src="state.dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%" />
            </el-dialog>
          </el-form-item>
        </el-form>
        <el-row style="display: flex;justify-content: space-between;margin-left: 120px">
          <el-button style="margin-right: 10px" size="large" type="primary" :icon="CirclePlus" @click="submitForm(formRef)">添加</el-button>
          <el-button style="margin-left: 10px" size="large" type="warning" :icon="Delete" @click="resetForm(formRef)">清空</el-button>
        </el-row>
      </el-card>

    </el-row>

    <GuiguLoading :is-loading="state.isAdding" text="正在添加，请稍等..."/>
  </div>
</template>

<script setup>

import {reactive, ref} from "vue";
import { Delete, Download, Plus, ZoomIn,CirclePlus} from '@element-plus/icons-vue'
import {TOKEN_HEADER} from "@/constant/app.js";
import useUserStore from "@/store/modules/user.js";
import {createUser} from "@/api/backend/user/user.js";
import {useRouter} from "vue-router";
import GuiguLoading from "@/components/GuiguLoading/index.vue";
import * as validator from '@/api/util/validator.js'
import {UPLOAD_PATH} from "@/constant/app.js";
import {ElMessage} from "element-plus";
import {getImgUrl} from "@/api/util/util.js";

const state=reactive({
  dialogImageUrl:'',
  dialogVisible:false,
  disabled:false,
  fileList:[],
  isAdding:false,
  isUploading:false,
  userAddInfo:{
    username: "",
    password: "",
    realname:"",
    email: "",
    phone: "",
    confirmPassword: "",
    encryptedType: "1",
    avatar:"",
    enabled: 1
  },
})

const uploadRef=ref()
const formRef=ref()
const userStore=useUserStore()




const rules = reactive({
  username: [
    { required: true, trigger: 'blur',validator:validator.isUsername},
  ],
  password:[
    {required:true,message:"密码不能为空",trigger:'blur'},
    {min:6, max: 20, message: "长度在6-20之间", trigger: 'change'}
  ],
  confirmPassword:[
    {required:true,message:"确认密码与密码不一致",trigger:'change',validator:validator.validateConfirmPassword(state.userAddInfo)}
  ],
  email:[
    {validator:validator.isEmail,trigger:'blur'}
  ],
  phone:[
    {validator:validator.isPhone,trigger:'blur'}
  ],
  avatar:[
  ]
})



const $router=useRouter()

const submitForm=(formRef)=>{

  formRef.validate((valid,fields) => {
    if (valid) {
      state.isAdding=true
      createUser(state.userAddInfo).then(res=>{
        $router.push("/user/list")
        state.isAdding=false
      }).catch(e=>{
        state.isAdding=false
      })
      return true
    } else {

      return false
    }
  })

}

const resetForm=(formEl)=>{
  formEl.resetFields()
  uploadRef.value.clearFiles()
}

const uploadHeaders=reactive({
  [TOKEN_HEADER]:userStore.userInfo.loginAccessToken
})
const handleRemove = (file,files) => {
  uploadRef.value.handleRemove(file)
}

const handlePictureCardPreview = (file) => {

  state.dialogImageUrl = file.url
  state.dialogVisible = true
}

const handleDownload = (file) => {
  // window.location.href=file.url
}

const uploadChange=(file,files)=>
{
  console.log('change')
}

const uploadRequest=(options)=>{

}

const beforeUpload=(file)=>{
  console.log('beforeUpload')
  try {
    state.isUploading=true
  }catch (e){
    console.log(e)
  }
  console.log(state.isUploading)
  return true
}

const uploadSuccess=(response,file,files)=>{
  state.isUploading=false
  file.url=getImgUrl(response.data)
  state.userAddInfo.avatar=response.data
}

const uploadError=(error,file,files)=>{
  state.isUploading=false
  state.userAddInfo.avatar=""
  ElMessage({
    type:"error",
    message:"头像上传失败,请重新上传",
    duration:3000
  })
}


</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}


</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>